package com.wits.media;

import android.graphics.Bitmap;
import android.graphics.ImageFormat;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

/**
 * Created by zhengboyuan on 2018-03-12.
 */

public class ImageFrameUtil {

    public static ImageFrame makeYv12(Bitmap bitmap) {
        ImageFrame frame = new ImageFrame();
        frame.format = ImageFormat.YV12;
        frame.width = bitmap.getWidth();
        frame.height = bitmap.getHeight();

        final int frameSize = bitmap.getWidth() * bitmap.getHeight();
        frame.data = new byte[frameSize * 3/ 2];

        ByteBuffer buffer = ByteBuffer.allocate(bitmap.getWidth() * bitmap.getHeight() * 4);
        bitmap.copyPixelsToBuffer(buffer);

        ColorConvert.rgb32ToYV12(buffer.array(), frame.data, bitmap.getWidth(), bitmap.getHeight());

        return frame;
    }


    public static boolean save(ImageFrame frame, String filepath) {
        try {
            File file = new File(filepath);
            OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
            os.write(frame.data);
            os.close();
            return true;
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return false;
    }


}
